<?php

namespace App\Formats;

use App\Common\Libs\ArrayHelper;
use App\Consts\GlobalConst;
use App\Models\UserCollect;

class CollectFormat extends BaseFormat
{
    public const PACKAGE_TARGET_LIST = 'packageTargetList';
    public const HOME_COLLECT_LIST = 'homeCollectList';

    public function formatCollectList($collects, $currentUserId, $formatScene)
    {
        switch ($formatScene) {
            case self::PACKAGE_TARGET_LIST:
            case self::HOME_COLLECT_LIST:
                return self::formatBySelfList($collects, $currentUserId);
        }

        return [];
    }

    public static function formatBySelfList($collects, $currentUserId)
    {
        $targetIdArr = ArrayHelper::getColumn($collects, 'target_id');

        $articleArr = formats()->ArticleFormat->formatArticleList($targetIdArr, $currentUserId, ArticleFormat::HOME_COLLECT_LIST);
        $articleArr = ArrayHelper::index($articleArr, 'id');

        $noteArr = formats()->NoteFormat->formatNoteList($targetIdArr, $currentUserId, NoteFormat::HOME_COLLECT_LIST);
        $noteArr = ArrayHelper::index($noteArr, 'id');

        $collectArr = CollectFormat::getCollectArrByTargetIds($currentUserId, $targetIdArr);

        $list = [];
        /**
         * @var UserCollect $collect
         */
        foreach ($collects as $collect) {
            if ($collect->target_type == GlobalConst::TARGET_TYPE_ARTICLE && isset($articleArr[$collect->target_id])) {
                $list[] = ArrayHelper::merge($articleArr[$collect->target_id], [
                    'collect_id' => $collect->collect_id,
                    'package_id' => $collect->package_id,
                    'created_at' => $collect->updated_at,
                    'target_type' => GlobalConst::TARGET_TYPE_ARTICLE,
                ]);
            }
            if ($collect->target_type == GlobalConst::TARGET_TYPE_NOTE && isset($noteArr[$collect->target_id])) {
                $list[] = ArrayHelper::merge($noteArr[$collect->target_id], [
                    'collect_id' => $collect->collect_id,
                    'package_id' => $collect->package_id,
                    'created_at' => $collect->updated_at,
                    'is_collect' => isset($collectArr[$collect->target_id]) && $collectArr[$collect->target_id]->is_deleted == GlobalConst::IS_NOT_DELETE,
                    'target_type' => GlobalConst::TARGET_TYPE_NOTE,
                ]);
            }
        }

        return $list;
    }

    public static function getCollectArrByTargetIds($userId, $targetIds, $select = ['target_id', 'is_deleted'])
    {
        $result = UserCollect::getModel($userId)
            ->select($select)
            ->where('user_id', $userId)
            ->whereIn('target_id', (array)$targetIds)
            ->get();

        return ArrayHelper::index($result, 'target_id');
    }
}
